package com.ruoyi.cqjd.service.impl;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

import com.ruoyi.cqjd.common.BaseContext;
import com.ruoyi.cqjd.common.CustomException;
import com.ruoyi.cqjd.domain.*;
import com.ruoyi.cqjd.dto.CqjdOrderDto;
import com.ruoyi.cqjd.service.*;
import org.apache.catalina.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.cqjd.mapper.CqjdOrdersMapper;
import org.springframework.transaction.annotation.Transactional;

/**
 * 订单Service业务层处理
 * 
 * @author ruoyi
 * @date 2022-06-19
 */
@Service
public class CqjdOrdersServiceImpl implements ICqjdOrdersService 
{
    @Autowired
    private CqjdOrdersMapper cqjdOrdersMapper;


    @Autowired
    private ICqjdShoppingCartService cqjdShoppingCartService;


//    @Autowired
//    private ShoppingCartService shoppingCartService;

    @Autowired
    private ICqjdUserService cqjdUserService;

//    @Autowired
//    private UserService userService;

    @Autowired
    private ICqjdAddressBookService cqjdAddressBookService;

//    @Autowired
//    private AddressBookService addressBookService;

    @Autowired
    private ICqjdOrderDetailService cqjdOrderDetailService;

//    @Autowired
//    private OrderDetailService orderDetailService;


//
//    @Autowired
//    private ShoppingCartService shoppingCartService;


    /**
     * 查询订单
     * 
     * @param id 订单主键
     * @return 订单
     */
    @Override
    public CqjdOrders selectCqjdOrdersById(Long id)
    {
        return cqjdOrdersMapper.selectCqjdOrdersById(id);
    }

    /**
     * 查询订单列表
     * 
     * @param cqjdOrders 订单
     * @return 订单
     */
    @Override
    public List<CqjdOrders> selectCqjdOrdersList(CqjdOrders cqjdOrders)
    {
        return cqjdOrdersMapper.selectCqjdOrdersList(cqjdOrders);
    }

    /**
     * 新增订单
     * 
     * @param cqjdOrders 订单
     * @return 结果
     */
    @Override
    public int insertCqjdOrders(CqjdOrders cqjdOrders)
    {
        return cqjdOrdersMapper.insertCqjdOrders(cqjdOrders);
    }

    /**
     * 修改订单
     * 
     * @param cqjdOrders 订单
     * @return 结果
     */
    @Override
    public int updateCqjdOrders(CqjdOrders cqjdOrders)
    {
        return cqjdOrdersMapper.updateCqjdOrders(cqjdOrders);
    }

    /**
     * 批量删除订单
     * 
     * @param ids 需要删除的订单主键
     * @return 结果
     */
    @Override
    public int deleteCqjdOrdersByIds(Long[] ids)
    {
        return cqjdOrdersMapper.deleteCqjdOrdersByIds(ids);
    }

    /**
     * 删除订单信息
     * 
     * @param id 订单主键
     * @return 结果
     */
    @Override
    public int deleteCqjdOrdersById(Long id)
    {
        return cqjdOrdersMapper.deleteCqjdOrdersById(id);
    }



    @Override
    @Transactional
    public void submit(CqjdOrders orders, Long userId) {
//        查询用户id
//        Long userId = BaseContext.getCurrentId();
//        查询购物车数据
//        LambdaQueryWrapper<ShoppingCart> queryWrapper=new LambdaQueryWrapper<>();
//        queryWrapper.eq(ShoppingCart::getUserId,userId);
//        List<ShoppingCart> list = shoppingCartService.list(queryWrapper);

        List<CqjdShoppingCart> list = cqjdShoppingCartService.getListByUserId(userId);

        if(list == null || list.size() == 0){
            throw new CustomException("购物车为空，不能下单");
        }


        //查询用户数据
//        User user = userService.getById(userId);

        CqjdUser user = cqjdUserService.selectCqjdUserById(userId);
        //查询地址数据
        Long addressBookId = orders.getAddressBookId();

//        AddressBook addressBook = addressBookService.getById(addressBookId);

        CqjdAddressBook addressBook = cqjdAddressBookService.selectCqjdAddressBookById(addressBookId);
        if(addressBook == null){
            throw new CustomException("用户地址信息有误，不能下单");
        }

        String orderStr=System.currentTimeMillis()+""+userId;
        Long orderId=Long.parseLong(orderStr.substring(0,10));//订单号
//        long orderId = IdWorker.getId();//订单号

        AtomicInteger amount = new AtomicInteger(0);


//                List<CqjdOrderDetail> orderDetails=new ArrayList<>();

        List<CqjdOrderDetail> orderDetails = list.stream().map((item) -> {
            CqjdOrderDetail orderDetail = new CqjdOrderDetail();
            orderDetail.setOrderId(orderId);
            orderDetail.setNumber(item.getNumber());
            orderDetail.setDishFlavor(item.getDishFlavor());
            orderDetail.setDishId(item.getDishId());
            orderDetail.setSetmealId(item.getSetmealId());
            orderDetail.setName(item.getName());
            orderDetail.setImage(item.getImage());
            orderDetail.setAmount(item.getAmount());
            amount.addAndGet(item.getAmount().multiply(new BigDecimal(item.getNumber())).intValue());
            return orderDetail;
        }).collect(Collectors.toList());


        orders.setId(orderId);
        orders.setOrderTime(new Date());
        orders.setCheckoutTime(new Date());
        orders.setStatus(2L);
        orders.setAmount(new BigDecimal(amount.get()));//总金额
        orders.setUserId(userId);
        orders.setNumber(String.valueOf(orderId));
        orders.setUserName(user.getName());
        orders.setConsignee(addressBook.getConsignee());
        orders.setPhone(addressBook.getPhone());
        orders.setAddress((addressBook.getProvinceName() == null ? "" : addressBook.getProvinceName())
                + (addressBook.getCityName() == null ? "" : addressBook.getCityName())
                + (addressBook.getDistrictName() == null ? "" : addressBook.getDistrictName())
                + (addressBook.getDetail() == null ? "" : addressBook.getDetail()));

//        添加记录到订单表

//        save(orders);
        insertCqjdOrders(orders);
//        添加记录到订单详情表
        cqjdOrderDetailService.saveBatch(orderDetails);
//        删除购物车
        cqjdShoppingCartService.removeByUserId(userId);
    }

    @Override
    public List<CqjdOrders> page(int page, int pageSize, Long userId) {
//        List<CqjdOrders> cqjdOrderDtos = cqjdOrdersMapper.page(page, pageSize, userId);
//        for (CqjdOrderDto cqjdOrderDto : cqjdOrderDtos) {
//            Long orderId = cqjdOrderDto.getId();
//            List<CqjdOrderDetail> orderDetails= cqjdOrderDetailService.getOrderDetailListByOrderId(orderId);
//            cqjdOrderDto.setOrderDetails(orderDetails);
//        }
        return cqjdOrdersMapper.page(page, pageSize, userId);
    }
}
